import { TENCENT_KEY } from "@/constants"
import { useEffect, useState } from "react"

const useTencentMap = (eleId: string) => {
  const [map, setMap] = useState<any>()

  useEffect(() => {
    if (map) return
    if (window.TMap?.Map) {
      const container = document.getElementById(eleId)
      const _map = new window.TMap.Map(container, {
        rotation: 20,//设置地图旋转角度
        pitch:30, //设置俯仰角度（0~45）
        zoom:12,//设置地图缩放级别
        center: new window.TMap.LatLng(33.98354324242736, 118.13343570263673)//设置地图中心点坐标 
      })
      setMap(_map)
      return
    }
    const script = document.createElement('script')
      script.type = 'text/javascript'
      script.src = `https://map.qq.com/api/gljs?v=2.exp&key=${TENCENT_KEY}`
      script.onerror = (err) => console.error(err)
      script.onload = () => {
        const container = document.getElementById(eleId)
        const _map = new window.TMap.Map(container, {
          rotation: 20,//设置地图旋转角度
          pitch:30, //设置俯仰角度（0~45）
          zoom:12,//设置地图缩放级别
          center: new window.TMap.LatLng(33.98354324242736, 118.13343570263673)//设置地图中心点坐标 
        })
        setMap(_map)
      }
      document.head.appendChild(script)
  }, [])

  return map
}

export default useTencentMap